package com.century.sjt.window;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.allinpay.appayassistex.APPayAssistEx;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.Pay.MerchantActivity;
import com.century.sjt.activity.setting.Forget_pwdPayActivity;
import com.century.sjt.activity.wallet.WalletRechareActivity;
import com.century.sjt.util.Base64Utils;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.gridpasswordview.GridPasswordView;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by 炳基 on 2016/7/26.
 */
public class RechargePwdWindow extends PopupWindow{
    private Context mContext;

    private GridPasswordView gpvCashPwd;
    private Button btn_ok;
    private View mMenuView;
    private TextView forger_pwd;

    private RequestQueue mQueue;
    private PayPwdWindowListItemClickListener listener;

    public RechargePwdWindow(Activity context, final String amount, final String BankCard, RequestQueue mQueue) {
        super(context);
        this.mContext= context;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.sjt_paypwd_window, null);
        this.mQueue = mQueue;
        gpvCashPwd=(GridPasswordView) mMenuView.findViewById(R.id.pay_cashpwd);
        forger_pwd=(TextView) mMenuView.findViewById(R.id.sjt_forget_pwd);
        forger_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("setpwd","3");
                intent.setClass(mContext, Forget_pwdPayActivity.class);
                mContext.startActivity(intent);
            }
        });

        btn_ok = (Button) mMenuView.findViewById(R.id.btn_payok);
        //确认按钮
        btn_ok.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                byte[] encodePwd = gpvCashPwd.getPassWord().getBytes();
                final String pwd = Base64Utils.encode(encodePwd);
//                listener.onPassWord(pwd);
//                listener.onCloseWindow(true);
                //销毁弹出框
//                gpvCashPwd.clearPassword();
//                dismiss();
                queryRecharData(amount,BankCard,"1",pwd);
            }
        });
        //设置按钮监听

        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mMenuView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = mMenuView.findViewById(R.id.pop_layout).getTop();
                int y=(int) event.getY();
                if(event.getAction()==MotionEvent.ACTION_UP){
                    if(y<height){
                        dismiss();
                    }
                }
                return true;
            }
        });
        gpvCashPwd.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onChanged(String psw) {

            }

            @Override
            public void onMaxLength(String psw) {
                byte[] encodePwd = gpvCashPwd.getPassWord().getBytes();
                final String apwd = Base64Utils.encode(encodePwd);

                //销毁弹出框a
//                gpvCashPwd.clearPassword();
                queryRecharData(amount,BankCard,"1",apwd);
//                dismiss();
            }
        });
    }
    /**
     * 获取充值订单
     */

    private void queryRecharData(final String amount, final String BankCard, final String type, final String pwd) {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, mContext.getResources().getString(R.string.error_please_waitting), mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.QueryRechareHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功

                        JSONObject Data = res.getJSONObject("data");
//                        Log.e("d",Data.toString());
//                        Log.e("text", Data.getString("issuerId") + "&" + Data.getString("tradeNature"));
                        String issuerId = Data.getString("issuerId");
                        String tradeNature = Data.getString("tradeNature");
                        String signType = Data.getString("signType");
                        String orderCurrency = Data.getString("orderCurrency");
                        String version = Data.getString("version");
                        String cardNo = Data.getString("cardNo");
                        String receiveUrl = Data.getString("receiveUrl");
                        String inputCharset = Data.getString("inputCharset");
                        String orderNo = Data.getString("orderNo");
                        String ext1 = Data.getString("ext1");
                        String orderAmount = Data.getString("orderAmount");
                        String signMsg = Data.getString("signMsg");
                        String payType = Data.getString("payType");
                        String merchantId = Data.getString("merchantId");
                        String language = Data.getString("language");
                        String orderDatetime = Data.getString("orderDatetime");
                        String productName = Data.getString("productName");

                        TipUtil.showToast(mContext.getResources().getString(R.string.recharg_success), mContext, 1);
                        listener.onCloseWindow(true);
                        dismiss();

                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), mContext, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("amount", amount);
                map.put("bankCardNo", BankCard);
                map.put("cashPwd", pwd);
                map.put("payMethod", type);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        mQueue.add(stringRequest);
    }
    public void setPayPwdWindowListItemClickListener(PayPwdWindowListItemClickListener listener) {
        this.listener = listener;
    }
    public interface PayPwdWindowListItemClickListener{
        /**
         * 支付方式事件监听
         * @param
         * @return
         */
        void onPassWord(String pwd);
        boolean onOpenWindow(boolean isdo);
        boolean onCloseWindow(boolean isdo);

    }

}
